<template>
  <layout-content
    :key="editState.operation"
    v-loading.fullscreen.lock="editState.loading"
    :header="headTitle"
    :back-to="{ name: editState.workloadType }"
  >
    <template #actions>
      <div>
        <el-button @click="routerBack()">
          {{ $t("commons.button.cancel") }}
        </el-button>
        <el-button v-if="!editState.showYaml" @click="onEditYaml">
          {{ $t("commons.button.edit_yaml") }}
        </el-button>
        <el-button v-if="editState.showYaml" @click="onCancelEditYaml">
          {{ $t("commons.button.back_form") }}
        </el-button>
        <el-button
          v-if="!editState.readonly"
          type="primary"
          @click="onCreateSource"
        >
          {{ $t("commons.button.confirm") }}
        </el-button>
      </div>
    </template>
    <div v-if="!editState.showYaml">
      <k-segment-tab index="base" label-width="120">
        <k-segment-tab-pane
          name="base"
          :label="$t('business.workload.general')"
        >
          <el-card class="el-card">
            <el-form ref="form" label-position="top" :model="editWorkload">
              <el-row :gutter="20">
                <el-col :span="12">
                  <k-form-item
                    v-model="editWorkload.metadata.name"
                    :label="$t('commons.table.name')"
                    prop="metadata.name"
                    :rules="editRules.name"
                    :disabled="editState.readonly || !operationIsCreate"
                    itemType="input"
                    content-class="w-full"
                    @change="onNameChanged"
                  />
                </el-col>
                <el-col :span="12">
                  <k-form-item
                    v-model="
                      editWorkload.metadata.annotations[
                        PresetAnnotationKey.Alias
                      ]
                    "
                    :label="$t('commons.table.alias')"
                    :prop="`metadata.annotations.${PresetAnnotationKey.Alias}`"
                    :disabled="editState.readonly || !operationIsCreate"
                    itemType="input"
                    content-class="w-full"
                  />
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item
                    :label="$t('business.namespace.namespace')"
                    prop="metadata.namespace"
                    :rules="editRules.select"
                  >
                    <KNamespaceSelector
                      v-if="operationIsCreate"
                      v-model:model-value="editWorkload.metadata.namespace"
                      editable
                      class="w-full"
                    />
                    <ko-data-item
                      v-else
                      v-model="editWorkload.metadata.namespace"
                      disabled
                      item-ype="flatSelect"
                      :selections="[]"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <ko-kv-table
                  ref="ko_annotation_label"
                  v-model:metadata="editWorkload.metadata"
                  v-model:selector="editWorkload.spec.selector"
                  :readonly="editState.readonly"
                  :resourceName="editWorkload.metadata.name"
                  :create="operationIsCreate"
                />
              </el-row>

              <el-row v-if="typeIs.statefulSet.value">
                <el-form-item
                  :label="$t('business.network.service_name')"
                  prop="spec.serviceName"
                >
                  <ko-data-item
                    v-model="editWorkload.spec.serviceName"
                    :disabled="readonly"
                    item-ype="flatSelect"
                    :selections="headlessServiceNames"
                  />
                </el-form-item>
              </el-row>
              <el-row v-if="typeIs.cronJob.value">
                <el-form-item
                  :label="$t('business.workload.schedule')"
                  prop="spec.schedule"
                  :rules="editRules.required"
                >
                  <ko-data-item
                    v-model="editWorkload.spec.schedule"
                    :disabled="readonly"
                    placeholder="0 * * * *"
                    itemType="input"
                  />
                </el-form-item>
              </el-row>
            </el-form>
          </el-card>
        </k-segment-tab-pane>
        <k-segment-tab-pane
          :label="$t('business.workload.containersOpts')"
          name="container"
        >
          <PodOptions
            v-model:model-value="editWorkload"
            :type="editState.workloadType"
            :readonly="editState.readonly"
            :node-list="source.nodeList.value"
            :config-map-list="source.configMapList.value"
            :secret-list="source.secretList.value"
            :service-list="source.serviceList.value"
            :cluster-list="source.clusterList.value"
          />
        </k-segment-tab-pane>
        <k-segment-tab-pane
          :label="$t('business.workload.storageOpts')"
          name="storage"
        >
          <PodVolume
            v-model:model-value="editWorkload"
            :type="editState.workloadType"
            :readonly="editState.readonly"
            :node-list="source.nodeList.value"
            :config-map-list="source.configMapList.value"
            :secret-list="source.secretList.value"
            :service-list="source.serviceList.value"
            :cluster-list="source.clusterList.value"
          />
          <el-row v-if="false" :gutter="20">
            <el-col v-if="typeIs.statefulSet.value" :span="editState.spanWidth">
              <el-card class="el-card">
                <template #header>
                  <span style="font-size: 14px; font-weight: bold">
                    {{ $t("business.workload.volume_claim_template") }}
                  </span>
                </template>
                <ko-volume-claim
                  ref="ko_volume_claim"
                  :readonly="editState.readonly"
                  :volumeClaimParentObj="editWorkload.spec"
                  :pvcList="source.pvcList.value"
                  :scList="source.storageClassList.value"
                  @loadVolumes="mergeVolumes"
                />
              </el-card>
            </el-col>
            <el-col :span="editState.spanWidth">
              <el-card class="el-card">
                <template #header>
                  <span style="font-size: 14px; font-weight: bold">
                    {{ $t("business.workload.volume") }}
                  </span>
                </template>
                <ko-volume
                  ref="ko_volume"
                  v-model:volumes="editPodSpec.volumes"
                  :readonly="editState.readonly"
                  :config-map-list="source.configMapList.value"
                  :pvc-list="source.pvcList.value"
                  :secret-list="source.secretList.value"
                  @loadVolumes="mergeVolumes"
                />
              </el-card>
            </el-col>
          </el-row>
        </k-segment-tab-pane>

        <k-segment-tab-pane
          :label="$t('business.workload.advanceOpts')"
          name="advance"
        >
          <!-- <ko-service-add ref="service_add" :serviceObj="editService" /> -->
          <PodAdvanceOptions
            v-model:model-value="editWorkload"
            :type="editState.workloadType"
            :readonly="editState.readonly"
            :node-list="source.nodeList.value"
            :config-map-list="source.configMapList.value"
            :secret-list="source.secretList.value"
            :service-list="source.serviceList.value"
            :cluster-list="source.clusterList.value"
          />
        </k-segment-tab-pane>
      </k-segment-tab>
    </div>
    <div v-if="editState.showYaml" class="grid-content bg-purple-light">
      <yaml-editor
        ref="yaml_editor"
        :value="yamlEditData"
        :is-edit="true"
        :readonly="editState.readonly"
      />
    </div>
    <div class="grid-content bg-purple-light" />
  </layout-content>
</template>

<script setup lang="ts">
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import KFormItem from "@/views/domain/kubeHud/views/components/k-form-item/index.vue";
import YamlEditor from "@/views/domain/kubeHud/views/components/yaml-editor/index.vue";
import KSegmentTabPane from "@/views/domain/kubeHud/views/components/KSegmentTab/KSegmentTabPane.vue";
import KSegmentTab from "@/views/domain/kubeHud/views/components/KSegmentTab/index.vue";

import KoKvTable from "@/views/domain/kubeHud/views/components/ko-workloads/ko-kv-table.vue";

import KoSpecBase from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-spec-base.vue";
import KoNodeSelector from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-node-selector.vue";
import KoPodScheduling from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-pod-scheduling.vue";
import KoTolerations from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-tolerations.vue";
import KoNetworking from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-networking.vue";
import KoSpecSecurity from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-spec-security.vue";
import KoUpgradeCommon from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-upgrade-common.vue";
import KoUpgradeJob from "@/views/domain/kubeHud/views/components/ko-workloads/ko-spec/ko-upgrade-job.vue";

import KoBase from "@/views/domain/kubeHud/views/components/ko-workloads/ko-base.vue";
import KoVolume from "@/views/domain/kubeHud/views/components/ko-workloads/ko-volume.vue";
import KoVolumeClaim from "@/views/domain/kubeHud/views/components/ko-workloads/ko-volume-claim.vue";
import KoContainer from "@/views/domain/kubeHud/views/components/ko-workloads/ko-container.vue";
import KoPorts from "@/views/domain/kubeHud/views/components/ko-workloads/ko-ports.vue";
import KoCommand from "@/views/domain/kubeHud/views/components/ko-workloads/ko-command.vue";
import KoEnvironment from "@/views/domain/kubeHud/views/components/ko-workloads/ko-environment.vue";
import KoResources from "@/views/domain/kubeHud/views/components/ko-workloads/ko-resources.vue";
import KoHealthCheck from "@/views/domain/kubeHud/views/components/ko-workloads/ko-health-check.vue";
import KoSecurityContext from "@/views/domain/kubeHud/views/components/ko-workloads/ko-security-context.vue";
import KoVolumeMount from "@/views/domain/kubeHud/views/components/ko-workloads/ko-volume-mount.vue";
import KoServiceAdd from "@/views/domain/kubeHud/views/components/ko-workloads/ko-service/ko-service-add.vue";
import KoSelect from "@/views/domain/kubeHud/views/components/ko-select.vue";
import PodVolume from "./widgets/PodVolume.vue";
import { checkPermissions } from "@/views/domain/kubeHud/utils/permission";
import {
  Container,
  InjectLabelKey,
  Namespace,
  NodeInfo,
  PresetAnnotationKey,
  useK8SApi
} from "../../../api/k8s";
import { computed, reactive, readonly, ref } from "vue";
import { useWorkloadEditor, WorkloadEditContainerType } from "./provider";
import KNamespaceSelector from "@/views/domain/kubeHud/views/components/KNamespaceSelector/index.vue";
import { read } from "fs";
import { nodeList } from "@/components/ReFlowChart/src/config";
import { ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
import { useFormRule } from "../../../utils/rules";
import { setObjectFromKey, setObjectFromKeys } from "../../../utils";
import PodOptions from "./widgets/PodOptions.vue";
import PodAdvanceOptions from "./widgets/PodAdvanceOptions.vue";

const {} = useFormRule();

const { t } = useI18n();

const podEditTabIndex = ref("Spec");
const podSpecEditTabIndex = ref("Scaling/Upgrade Policy");
const containerEditTabIndex = ref("General");

const editCardIndex = ref("base");

const {
  editState,
  editWorkload,
  editContainer,
  editSpec,
  editPodSpec,
  editService,
  editMetadata,
  editRules,
  routerBack,

  source,
  headlessServiceNames,

  typeIs,
  containerTypeIs,
  operationIsCreate,
  serviceEditable,

  loadWorkloadDetails,
  reloadClusterList,
  reloadConfigMapList,
  reloadNamespaces,
  reloadNodes,
  reloadServiceList,
  reloadStorageClassList,
  mergeVolumes,
  reloadPvcList,
  updateContainerName,
  createWorkload
} = useWorkloadEditor();

const yamlEditData = ref({
  apiVersion: "v1",
  kind: "List",
  items: []
});

const headTitle = computed(() => {
  return `${operationIsCreate.value ? t("commons.button.add") : t("commons.button.edit")} ${editState.workloadType}`;
});

// TODO: namespace changed
const onNameChanged = (ns: string) => {
  return;
  console.log("onNameChanged ", this, ns);
  setObjectFromKeys(
    editWorkload.value,
    ["metadata", "labels", InjectLabelKey.AppName],
    ns
  );
  setObjectFromKeys(
    editWorkload.value,
    ["spec", "selector", "matchLabels", InjectLabelKey.AppName],
    ns
  );
};

const onEditYaml = () => {
  yamlEditData.value.items = [];
  if (editWorkload.value) {
    yamlEditData.value.items.push(editWorkload.value);
  }
  if (editService.value) {
    yamlEditData.value.items.push(editService.value);
  }
  editState.showYaml = true;
};

const onCreateSource = () => {
  console.log("createSource", editWorkload.value);
  // createWorkload();
  //TODO:
};
const onCancelEditYaml = () => {
  ElMessageBox.alert(
    t("commons.confirm_message.back_form"),
    t("commons.message_box.prompt"),
    {
      confirmButtonText: t("commons.button.confirm"),
      cancelButtonText: t("commons.button.cancel"),
      type: "warning"
    }
  ).then(() => {
    editState.showYaml = false;
  });
};

const onEditContainerChanged = (
  type: WorkloadEditContainerType,
  index?: number,
  item?: Container
) => {
  editState.currentContainerIndex = index;
  editState.currentContainerType = type;
};

const onAddContainer = (
  type?: WorkloadEditContainerType,
  container?: Container
) => {
  switch (type) {
    case WorkloadEditContainerType.Init:
      if (!editPodSpec.value.initContainers) {
        editPodSpec.value.initContainers = [];
      }
      editPodSpec.value.initContainers.push(container ?? {});
      break;
    case WorkloadEditContainerType.Standard:
      if (!editPodSpec.value.containers) {
        editPodSpec.value.containers = [];
      }
      editPodSpec.value.containers.push(container ?? {});
  }
};

const onDeleteContainer = (
  type?: WorkloadEditContainerType,
  index?: number
) => {
  switch (type) {
    case WorkloadEditContainerType.Init:
      editPodSpec.value.initContainers.splice(index, 1);
      break;
    case WorkloadEditContainerType.Standard:
      editPodSpec.value.containers.splice(index, 1);
  }
};
</script>

<style scoped>
.row-box {
  display: flex;
  flex-flow: wrap;
}

.row-box .el-card {
  min-width: 100%;
  height: 100%;
  margin-right: 20px;
  padding: 0px;
  --el-card-padding: 15px;

  border: 0px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
</style>
